Adding new base_query_class arg for associations. #1006
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #85
This PR adds a new arg that allows you to set the query class used for querying your association. This can be used in conjunction with soft_deleted records to ensure every preload you do only preloads the kept records.
The default base_query_class is always
T::BaseQuery
, but with soft_deleted models, you would have to either monkey-patchT::BaseQuery
, or skip using preloads to avoid cases where you would preload a soft deleted record.Currently this PR is only adding in
has_many
andhas_many :through
associations. If this works out, we can work outhas_one
, but I'm not sure ifbelongs_to
would need this or not 🤔Side note
There is an edge case that comes up with this. Each association has an extra
_count
method that returns the total count of that association. It uses thebase_query_class
to run aselect_count
. If you use the escape hatch to preload more records than the base query uses, your_count
method will return more or less than what you've preloaded.Side note 2
How the joins are built when using "has many through" is a bit complex. You generally preload your has_many query, but then that one needs to preload the join internally. If you need an escape hatch out of that default setup, I've added some new args to the preload methods here.